<?php

// 保证金

namespace app\mobile\controller;

use think\Db;
use think\Request;
use think\Session;
use think\Controller;
use app\mobile\model\MemberAuction;
use app\mobile\model\Member as MemberModel;
use app\mobile\model\Auction as AuctionModel;
use app\mobile\model\AuctionGoods as AuctionGoodsModel;
use app\mobile\model\MemberAuction as MemberAuctionModel;
use think\Loader;

class Bond extends Controller
{

    public function news($order_number,$openid,$pay_account,$pay_name){
//        halt("{" .
//            "\"out_biz_no\":\"$order_number\"," .
//            "\"payee_type\":\"ALIPAY_LOGONID\"," .
//            "\"payee_account\":\"$openid\"," .
//            "\"amount\":\"$pay_account\"," .
//            "\"payer_show_name\":\"善食元商城支付宝提现\"," .
//            "\"payee_real_name\":\"\"," .
//            "\"remark\":\"提现\"" .
//            "}");
        Loader::import('alipay.AopSdk');
        Loader::import('alipay.aop.request.AlipayFundTransToaccountTransferRequest');
        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2018053160276379';
        $aop->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDKv2VTYspqx5T02ySirITgUD9LYX9u29ditZdHoEnqC41Kk+DydsMO84QhOIJGUx4Am3AWTg7MJHb3BtonKJ8rAlVcOxHGFRhC8rxpGRPnAkvZZmpFLjCkOgnKf+qps5vw8yTteFjhon7lpGCrJtykY4s7+wvc0jiN3isWDGkFq3keqiZV7+nK4QW0JqHxJF0pVQboeu2+Ni8mo9S+Ej5CoijCiZgqqff0h25uaNEcNzbrnjv0a/L0JjSxo3m5ILT3+30wc5g8hZ3gVqW9NhLNmV+bh3YgYXJgcFwlLrBeTdsebBdGn1VpBSQvz2w5OnXxNXuIQSLG1qlD0QDFllyTAgMBAAECggEBALsMJMDvTWuBway8WGoz20rO/fXfdx+hdm48tdqAyHBCRBHfqBJI+t/aTbYQWi/jErTgsmIBlalEovR3v9+MnHujZXj3jgg/AekR5DzZxADFn5Br6fL1EC8S1GGb7bSu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6cNnXgUf';
        $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArkvOKDcsDkvMTpYuuA3QnY6pn3g8Uej9Lp4JRw64EjVi87nTE2YZCHRpQBSkC99yCRwqx7FO9GcKP2tT4GrdK0mWOiV5z1y2s6fj4DRreCsGrwH1640jLjEiJL4+byxKeqWE0m4K9Mpa3Jx/IGxDhAhAMILnuWPrRBjhiORygalHvPHO2q1pKAXrewrMRS7zxlbjUp3KHIaL8QVBQa0GbIc/chBGauJ+sqorRVO+2l0zuwLLuNXhaVaAWXoomPFQRS2SFQf8ubE7Io4nWRNXqVQR7k52fG6dBH7kMnAzsPRn7g88t3FXHt86gAG/SXfzgKN/1ubVz14iyfVWL8AbbwIDAQAB';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayFundTransToaccountTransferRequest();
        $request->setBizContent("{" .
            "\"out_biz_no\":\"$order_number\"," .
            "\"payee_type\":\"ALIPAY_LOGONID\"," .
            "\"payee_account\":\"$openid\"," .
            "\"amount\":\"$pay_account\"," .
            "\"payer_show_name\":\"善食元商城支付宝提现\"," .
            "\"payee_real_name\":\"$pay_name\"," .
            "\"remark\":\"提现\"" .
            "}");
        $result = $aop->execute ($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return true;
        } else {
            $resultMsg = $result->$responseNode->sub_msg;
            return $resultMsg;
        }
    }
    /*
     * 保证金充值
     */
    public function index()
    {
        $auction_goods_id = Request::instance()->param('goods_id');
        $info = (new MemberModel)->where('id', Session::get('member_id'))->field('username,wechat_id')->find();
        $bond = (new AuctionGoodsModel())->where('id', $auction_goods_id)->find();
        $pass = (new MemberModel)->where('id', Session::get('member_id'))->value('pay_pass');


        return $this->fetch('', [
            'bond' => $bond,
            'pass' => $pass,
            'info' => $info,
        ]);

    }


    /*
     * 余额支付保证金
     */
    public function balance()
    {
        if (Request::instance()->isPost()) {
            // 获取保证金金额
            $price = Request::instance()->param('price');
            // 会员ID
            $member_id = Session::get('member_id');
            // 拍卖商品ID
            $goods_id = Request::instance()->param('goods_id');
            // 支付密码
            $pwd = Request::instance()->param('pwd');
            $pass = (new MemberModel())->where('id', Session::get('member_id'))->value('pay_pass');
            // 验证密码
            if (md5(md5($pwd)) != $pass) {
                return ['code' => 400, 'message' => '密码不正确'];
            }

            $find = (new AuctionGoodsModel())->where('id', $goods_id)->find();

            $blance_price = Db::name('member')->where('id', $member_id)->value('balance');
            if ($blance_price<$price) return ['code'=>404,'message'=> '余额不足'];

            Db::startTrans();
            try {

                // 会员拍卖纪录增加
                $ini = [
                    'auction_id'    => $find['auction_id'],
                    'goods_id'      => $goods_id,
                    'member_id'     => $member_id,
                    'reserve_price' => $price,
                    'status'        => 2
                ];

                (new MemberAuction)->allowField(true)->save($ini);

                // 减少余额

                Db::name('member')->where('id', $member_id)->setDec('balance', $price);

                $con = [
                    'member_id'=>  $member_id,
                    'type_id'  => 3,
                    'price'    => $price,
                    'way'      => '保证金充值',
                    'balance'  => $blance_price,
                    'status'   => 1,
                    'reason'   => '',
                    'order_number'  => self::createNumber(),
                    'create_time'  => time(),
                ];

                Db::name('member_withdraw')->insert($con);

                Db::commit();

                return ['code'=>200,'message'=> '支付成功'];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['code'=>404,'message'=> '支付失败'];
            }
        }
    }


    /**
     * 生成订单号
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }






}